<?php
declare(strict_types=1);
namespace app\admin\service\user;

use app\common\model\User;
use app\common\model\UserCate;
use app\common\service\BaseService;

/**
 * 用户 用户分组 服务类
*/
class UserService {
    /**
     * 添加/编辑 用户
     */
    public static function saveOrEditUser($params,$admin_id){
        //id 大于0 时为编辑
        if (isset($params['id']) && $params['id'] > 0) {
            //编辑
            $params['state'] = $params['state'] ? 1 : 0;
            $params['cancel'] = $params['cancel'] ? 1 : 0;
            $model = User::field('id,cate_id,nickname,state,cancel,avatar')->with('UserCate')->find($params['id']);
            if ($model) {
                $model->save($params);
                return suc('成功',$model);
            }
            return suc('非法操作','',1);
        }
        //添加
        unset($params['id']);

        $model = new User();
        $params['state'] = 1;
        $params['cancel'] = 1;
        $params['openid'] = 'kf';
        $params['username'] = '1'.random_int(3000000000, 9999999999);
        $model->save($params);
        //生成uid
        $model->uid = $model->id . random_int(1111, 99999);
        $model->save(); //更新
        $model->UserCate = UserCate::field('id,name')->find($model->cate_id);
        return suc('成功',$model);
    }

    /**
     * 添加/编辑 用户分组
    */
    public static function saveOrEditUserCate($params){
        //id 大于0 时为编辑
        if (isset($params['id']) && $params['id'] > 0) {
            //编辑
            $params['state'] = $params['state'] ? 1 : 0;
            $model = UserCate::field('id,name,des,state')->find($params['id']);
            if ($model) {
                $model->save($params);
                return suc('成功',$model);
            }
            return suc('非法操作','',1);
        }
        //添加
        unset($params['id']);
        $model = new UserCate();
        $params['state'] = 1;
        $model->save($params);
        return suc('成功',$model);
    }
}